import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    goodList: [
      {
        name: '诸葛亮',
        price: 1000,
        num: 1,
        checked: false
      },
      {
        name: '蔡文姬',
        price: 1500,
        num: 1,
        checked: false
      },
      {
        name: '妲己',
        price: 2000,
        num: 1,
        checked: false
      },
      {
        name: '鲁班',
        price: 2200,
        num: 1,
        checked: false
      }
    ]
  },
  mutations: {
    del (state, payload) {
      state.goodList.splice(payload, 1)
    },
    addNum (state, payload) {
      state.goodList[payload].num++
    },
    subNum (state, payload) {
      if (state.goodList[payload].num <= 1) {
        return 1
      }
      state.goodList[payload].num--
    },

    setAll (state, payLoad) {
      state.goodList.forEach(item => {
        item.checked = payLoad
      })
    },
    addNewList (state, payload) {
      if (payload.name === '' || payload.price === '' || payload.num === '') {
        return alert('请输入内容')
      }
      if (typeof (payload.price) !== 'number' || typeof (payload.num) !== 'number') {
        return alert('请输入正确格式')
      }
      state.goodList.push(payload)
    }
  },
  actions: {
  },
  getters: {
    getAll (state) {
      return state.goodList.every(item => item.checked === true)
    },
    totalPrice (state) {
      return state.goodList.reduce((sum, item) => {
        if (item.checked) {
          sum += item.price * item.num
        }
        return sum
      }, 0)
    }
  },
  modules: {
  }
})
